<template>
    <!-- 认证医生是否合法的 -->
    <section v-if="isShow">
        <div>
            <div class="form-group">
                <formCell v-model="formData.username" class="form-item" title="姓名" placeholder="输入姓名" tag="input"/>
            </div>

            <div class="form-group">
                <formCell v-model="formData.phone" class="form-item" title="联系方式" placeholder="请输入手机号码" tag="input"/>
            </div>

            <div class="form-group">
                <formCell v-model="formData.remark" class="form-item" title="验证码" placeholder="请输入验证码" tag="input"/>
                <div class="btn-sms" v-if="downtime<60">{{downtime+"s后重试"}}</div>
                <div class="btn-sms" @click="apiSmscode" v-else>发送验证码</div>
            </div>

            <div class="form-group">
                <formCell v-model="formData.id" class="form-item" title="身份证号" placeholder="输入身份证号码" tag="input"/>
            </div>
        </div>

        <div class="upload-idcard">
            <h3 class="h3">请上传二代身份证原件照片</h3>
            <div class="upload-wrap">
                <input @click="chooseImage(1)" class="upload-input">
                <img class="img" :src="formData.imgHead||bgimgHead" alt="">
            </div>
            <div class="upload-wrap">
                <input @click="chooseImage()" class="upload-input">
                <img class="img" :src="formData.imgBack||bgimgBack" alt="">
            </div>
        </div>

        <div class="btn-group" style="background-color: white;margin-top: 10px;" @click="protocol">
            <div class="form-group" style="height: 30px;text-align: left;padding: 10px 0">
                <nut-radio size="base"><a href="javascript:;">用户协议</a></nut-radio>
            </div>
            <button class="btn btn-submit" @click="onSubmit">确定</button>
        </div>

    </section>
</template>

<script>
    /* eslint-disable no-console,no-unused-vars,no-undef */

    import formCell from "@/components/common/formCell.vue";

    const components = {formCell};
    export default {
        components,
        data() {
            return {
                isFirst: true,
                isShow: false,
                formData: {
                    username: "",
                    id: "",
                    remark: "",
                    phone: "",
                    imgHead: "",
                    imgBack: "",
                },
                bgimgHead: require("@/assets/images/idcard-front.png"),
                bgimgBack: require("@/assets/images/idcard-reverse.png"),
                downtime: 60, //倒计时时间
            }
        },
        created() {
            console.log(this);
            let _that = this;
            let f = setInterval(function () {
                console.log("==========setInterval  created=============");
                if (_that.isFirst && _that.$store.state.doctor == null && _that.$store.state.inited) {
                    _that.isFirst = false;
                    _that.isShow = true;
                    clearInterval(f);
                    _that.initWechat();
                }
            }, 100);
        },
        updated() {
            if (this.$store.state.doctor == null && this.$store.state.inited) {
                this.isShow = true;
                this.initWechat();
            }
        },
        watch: {},
        methods: {
            protocol:function(){
                this.$router.push({name: 'protocol'});
            },
            initWechat: function () {
                this.API.get(this.ApiUrl.GET_WECHAT, {
                    params: {
                        openid: this.$store.state.openid,
                        url: window.location.href.split("#")[0]
                    }
                }).then(({data}) => {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.data.appId, // 必填，公众号的唯一标识
                        timestamp: data.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: data.data.nonceStr, // 必填，生成签名的随机串
                        signature: data.data.signature,// 必填，签名
                        jsApiList: [
                            "chooseImage",
                            "previewImage",
                            "uploadImage",
                            "downloadImage"
                        ] // 必填，需要使用的JS接口列表
                    });
                    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用

                    });
                    wx.error(function (res) {
                        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，
                        // 也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                        /*vm.$toast.text("微信初始化失败:" + JSON.stringify(res));
                        vm.initWechat();*/
                    });
                }).catch(err => {
                    console.log(err);
                    //请求异常，重试
                    vm.initWechat();
                });
            },
            upload: function (mediaId, seq) {
                this.API.put(this.ApiUrl.PUT_UPLOAD + "?mediaId=" + mediaId).then(({data}) => {
                    if (data.code === 1200) {
                        if (seq === 1) {
                            this.formData.imgHead = data.data;
                            this.$toast.text('身份证正面已上传成功');
                        } else {
                            this.formData.imgBack = data.data;
                            this.$toast.text('身份证背面已上传成功');
                        }
                    }
                }).catch(err => {
                    console.log("upload::err------", err);
                    this.$toast.text('图片上传失败，请重试::' + JSON.stringify(res));
                    this.upload(mediaId, seq);
                });
            },
            chooseImage: function (seq) {
                let _that = this;
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 指定是原图还是压缩图，默认都有
                    sourceType: ['camera', 'album'], // 指定来源是相册还是相机，默认都有
                    success: function (res) {
                        let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片

                        if (seq === 1) {
                            _that.formData.imgHead = localIds;
                            _that.bgimgHead = localIds;
                        } else {
                            _that.formData.imgBack = localIds;
                            _that.bgimgBack = localIds;
                        }

                        //android bug 需要等待1s 执行
                        setTimeout(function () {
                            wx.uploadImage({
                                localId: localIds.toString(), // 需要上传的图片的ID，由chooseImage接口获得
                                isShowProgressTips: 1, // 进度提示
                                success: function (res) {
                                    let mediaId = res.serverId; // 返回图片的服务器端ID，即mediaId
                                    //将获取到的 mediaId 传入后台 方法savePicture
                                    _that.upload(mediaId, seq);
                                },
                                fail: function (res) {
                                    this.$toast.text('图片上传失败，请重试::' + JSON.stringify(res));
                                }
                            });
                        }, 100);
                    }
                })
            },
            onSubmit() {
                let {phone, remark, id, imgHead, imgBack, username} = this.formData;
                if (!username) {
                    this.$toast.text("请输入姓名");
                    return;
                } else if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
                    this.$toast.text("输入的手机号不正确");
                    return;
                } else if (!remark) {
                    this.$toast.text("请输入验证码");
                    return;
                } else if (!id) {
                    this.$toast.text("请输入身份证号");
                    return;
                }

                //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
                var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
                if (reg.test(id) === false) {
                    this.$toast.text("请输入合法的身份证号");
                    return;
                }

                this.API.POST("/drs/doctorApply", {
                    phone: phone,
                    imgHead: imgHead,
                    imgBack: imgBack,
                    name: username,
                    idCard: id,
                    remark: remark,
                    openid: this.$store.state.openid,
                    isDelete: 2
                }).then(({data, status}) => {
                    // this.$router.push({
                    //   name:"doctorInfo"
                    // })
                    this.$toast.text("系统验证中，请留意信息提示");
                })

            },
            // 发送验证码
            apiSmscode() {

                let {phone} = this.formData;
                if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
                    this.$toast.text("手机号码格式不正确！")
                    return;
                }
                // 启动验证码计时器
                let id = setInterval(() => {
                    this.downtime--;
                    if (this.downtime < 0) {
                        this.downtime = 60;
                        clearInterval(id);
                    }
                }, 1000)
                this.API.GET("/drs/phone", {
                    params: {
                        phone
                    }
                }).then(({data, status}) => {
                    if (+data.code === 1200) {
                        this.$toast.text("验证码发送成功，请留意短信")
                    }
                })
            },
        }
    }
</script>

<style>
    #app {
        background-color: #eee;
    }

    .form-group {
        padding: 0px 10px;
        font-size: 16px;
        background-color: #fff;
        position: relative;
    }

    .form-group:last-child .form-item {
        border-bottom: none;
    }

    .form-group .btn-sms {
        position: absolute;
        right: 13px;
        top: 50%;
        font-size: 13px;
        color: #fff;
        transform: translateY(-50%);
        background-color: #2D90DE;
        border: none;
        border-radius: 10px;
        padding: 5px 10px;
    }

    .form-group .form-item {
        padding: 15px 0px;
        border-bottom: 1px solid #ccc;
        text-align: left;
    }

    .upload-idcard {
        margin-top: 12px;
        padding: 20px;
        background-color: #fff;
        text-align: center;
    }

    .upload-idcard h3.h3 {
        font-size: 14px;
        font-weight: normal;
        margin: 0;
        text-align: left;
    }

    .upload-idcard .img {
        width: 80%;
        margin-top: 20px;
    }

    .upload-idcard .upload-wrap {
        position: relative;
        overflow: hidden;
    }

    .upload-idcard .upload-wrap .upload-input {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 2;
        opacity: 0;
        left: 0;
        top: 0;
    }

    .btn-group {
        padding: 40px 20px;
    }

    .btn-group .btn.btn-submit {
        width: 100%;
        height: 46px;
        border: 0;
        font-size: 14px;
        color: #fff;
        border-radius: 3px;
        background-color: #2D90DE;
    }
</style>

